﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using XCommunity.Documents;
using XCommunity.Frames;
using XCommunity.Data;
using XCommunity.Forums.Views;
using XCommunity.Web.UI;
using XCommunity.Web;

public partial class Forums_Presenters_TopicFramePresenter : System.Web.UI.UserControl
{
  public ITopicFrame Topic
  {
    get { return View.Topic; }
  }


  public TopicFrameView View
  {
    get { return (TopicFrameView) this.GetView(); }
  }


  private Presenter_DocumentsPagingControl pagingControl1;
  private Presenter_DocumentsPagingControl pagingControl2;

  private IPagingData<PostFrameView> responsesPaging;

  protected void Page_Init( object sender, EventArgs e )
  {
    pagingControl1 = (Presenter_DocumentsPagingControl) LoadControl( "~/Presenter/DocumentsPagingControl.ascx" );
    pagingControl2 = (Presenter_DocumentsPagingControl) LoadControl( "~/Presenter/DocumentsPagingControl.ascx" );

    responsesPaging = View.Responses.ToPagingSource().CreatePaging( 30 );

    pagingControl1.PagingData = responsesPaging;
    pagingControl2.PagingData = responsesPaging;

    Controls.AddAt( Controls.IndexOf( PostList ), pagingControl1 );
    Controls.AddAt( Controls.IndexOf( PostList ) + 1, pagingControl2 );
  }


  protected void Page_Load( object sender, EventArgs e )
  {
    Presenter themePresenter = new Presenter( View.Theme );
    themePresenter.Controls.Add( LoadControl( "~/Forums/PostFramePresenter.ascx" ) );

    PostList.Controls.Add( themePresenter );


    foreach ( PostFrameView response in responsesPaging.GetPage( pagingControl1.PageIndex ) )
    {
      Presenter responsePresenter = new Presenter( response );
      responsePresenter.Controls.Add( LoadControl( "~/Forums/PostFramePresenter.ascx" ) );
      PostList.Controls.Add( responsePresenter );
    }


    if ( WebCommunityContext.CurrentCommunityContext.CurrentAccount == null )
      AttatchTopicForm.Visible = false;

  }

  protected void OnAttatchTopic( object sender, EventArgs e )//当发布留言时
  {

    IHtmlDocumentProvider documentProvider = WebCommunityContext.Current.GetDefaultDocumentProvider();//首先获取默认的文档处理引擎
    //这里获取到的就是一个TextDocumentProvider，它用于创建和显示纯文本文档，由于实现了IHtmlDocumentProvider，它可以用于网站。

    Dictionary<string, string> meta = new Dictionary<string, string>() { { "Caption", TitleTextBox.Text } };//创建元数据集合，这里只有一个标题
    Document document = documentProvider.CreateDocument( ContentTextBox.Text, meta );//创建文档对象

    WebCommunityContext.CurrentCommunityContext.DocumentService.SaveDocument( document );//然后是将文档保存下来

    View.Topic.AttachTopic( document );//最后将这个文档加入到这个ThreadFrame（主题）。

    Response.Redirect( Request.Url.ToString() );//重新呈现这个话题

  }

}
